
//启用jQuery标志
let $ = jQuery
//表格数据源
//受限用户
let dataSourceControl= $('#dataSourceControl').attr("action")
let controlMethod = ''
let flushControlDataSource = ''

//自由用户
let dataSourceUncontrol = $('#dataSourceUnControl').attr("action")
let flushUnControlDataSource = ''
let unControlMethod = ''

//用户名匹配模式：字母开头,允许5-16字节，允许字母数字下划线
function checkName(name){
    return new RegExp('^[a-zA-Z][a-zA-Z0-9_]{4,15}$').test(name)
}
//id匹配模式：非负正整数
function checkId(id) {
    return new RegExp('^([1-9][0-9]*)$').test(id)
}
//--------------------------------------------------------------受限用户表---------------------------------------------------------------------------
let myTableControl = {
    table:layui.table,
    tableFlush: function(dataSourceUrl,sendMethod){
        this.table.render({
            elem:'#dataTableControl'
            ,cellMinWidth: 100
            ,height: 616
            ,method: sendMethod //请求方式
            ,url: dataSourceUrl //数据接口
            ,page: true//开启分页
            ,autoSort:true
            ,limit:14
            ,size:'lg'
            ,even:true
            ,response:{
                statusCode: 200,
            }
            //动态数据表格
            //如果响应数据格式不符合layui默认要求，则需要用到phraseData
            ,cols: [ [ //表头,两个括号间的空格不能去
                {type:'checkbox',width: '6%'},
                {field: 'index', title: '序号', width:'10%', unresize:true, sort: true },
                {field: 'userId', title: 'ID', width:'22%',unresize:true},
                {field: 'userName', title: '用户名', width:'16%',unresize:true},
                {field: 'startDate', title: '起始日期', width:'23%',unresize:true},
                {field: 'endDate', title: '结束日期', width:'23%',unresize:true},
            ] ]

        })

    }
}


//转到界面以后默认的数据源
layui.use('table',function () {
    controlMethod = 'get'
    flushControlDataSource = dataSourceControl
    myTableControl.tableFlush(dataSourceControl,controlMethod)

})



/*
-----------------------------------增删改查事务处理----------------------------------
 */

//选取日期范围
layui.use('laydate',function () {
    let laydate = layui.laydate;

    //获取日期并将数据存入Vue框架
    laydate.render({
        elem:'#dateRangeControl',
        range:['#startDateControl','#endDateControl'],
        done:function (value,date,endDate) {
            let start = JSON.parse(JSON.stringify(date))
            let end = JSON.parse(JSON.stringify(endDate))
            if(!(value === '' || value === undefined || value === null)){
                selectControlVue.$data.startDate = start.year+'-'+start.month+'-'+start.date
                selectControlVue.$data.endDate =  end.year+'-'+end.month+'-'+end.date
            }else{
                selectControlVue.$data.startDate = ''
                selectControlVue.$data.endDate =  ''
            }

        },
    })

    //获取日期并将数据存入editVue框架
    laydate.render({
        elem:'#editDateRange',
        range:['#editStartDate','#editEndDate'],
        type: 'datetime',
        min:new Date().toLocaleDateString(),//最小日期设置为当前服务器时间
        done:function (value,date,endDate) {
            let start = JSON.parse(JSON.stringify(date))
            let end = JSON.parse(JSON.stringify(endDate))
            if(!(value === '' || value === undefined || value === null)){
                let editStartDate = start.year+'-'+start.month+'-'+start.date+' '+start.hours+":"+start.minutes+":"+start.seconds
                let editEndDate =  end.year+'-'+end.month+'-'+end.date+' '+end.hours+":"+end.minutes+":"+end.seconds
                modifyVue.$data.startDate = editStartDate
                modifyVue.$data.endDate = editEndDate
            }else{
                modifyVue.$data.startDate = ''
                modifyVue.$data.endDate =  ''
            }

        },

    })
})

//利用Vue框架监听数据处理类事件并生成请求
let selectControlVue = new Vue({
    el:'#selectControlSubmit',
    data:{
        message:'',
        startDate:'',
        endDate:'',
        selectedData:[]
    },

    methods:{
        //触发查询事件
        selectControlClick :function (event) {
            let choice = $("[name='userChoice']")
            let realChoice = ''
            //根据单选框的选择来设置查询条件
            for(let i = 0;i<choice.length;i++){
                if (choice[i].checked) realChoice = choice[i].value
            }
            if(realChoice  === 'byName'){ //用户名匹配模式
                if(this.message === ''){
                    layer.msg("请输入用户名！",{
                        time:1500
                    })
                }else if (!checkName(this.message)){
                    layer.msg("用户名非法！",{
                        time:1500
                    })
                }else {
                    let url = $('#selectControlVisitor').attr("action")+realChoice+"/"+this.message+"/"+0
                    flushUrl = url
                    controlMethod ='get'
                    myTableControl.tableFlush(url,controlMethod)
                    layer.msg("已获取信息！",{
                        time:1500
                    })
                }

            }else if(realChoice === 'byId'){//id匹配模式
                if(this.message === ''){
                    layer.msg("请输入ID号！",{
                        time:1500
                    })
                }else if (!checkId(this.message)){
                    layer.msg("ID号非法！",{
                        time:1500
                    })
                }else {
                    let url = $('#selectControlVisitor').attr("action")+realChoice+"/"+this.message+"/"+0
                    flushUrl = url
                    controlMethod ='get'
                    myTableControl.tableFlush(url,controlMethod)
                    layer.msg("已获取信息！",{
                        time:1500
                    })
                }
            }else if(realChoice === 'byDate'){
                if(this.startDate ==='' || this.endDate ===''){
                    layer.msg("请选择起止日期！",{
                        time:1500
                    })
                }else{
                    let url = $('#selectControlVisitor').attr("action")+realChoice+"/"+this.startDate+"/"+this.endDate
                    flushUrl = url
                    controlMethod ='get'
                    myTableControl.tableFlush(url,controlMethod)
                    layer.msg("已获取信息！",{
                        time:1500
                    })

                }

            }
        },

        //删除事件
        deleteControlClick: function(event) {
            let checkedData = selectControlVue.$data.selectedData
            if(checkedData.length === 0){
                layer.msg("请选择数据项！",{
                    time:1500
                })
            }else {
                layer.confirm("真的要删除么？您其实可以直接修改权限日期。",function (index) {
                    layer.close(index)
                    let url = $('#deleteControlVisitor').attr('action')
                    axios({
                        url:url,
                        method: 'delete',
                        data:{
                            deleteInfo: checkedData
                        }
                    }).then(function (response) {
                        layer.msg(JSON.stringify(response.data),{
                            time:1500
                        })
                        myTableControl.tableFlush(dataSourceControl,controlMethod)
                    })
                })
            }
        },

        //修改按钮点击事件
        controlModify:function(event) {
            let checkedData = selectControlVue.$data.selectedData
            if(checkedData.length === 0){
                layer.msg("请选择数据项！",{
                    time:1500
                })
            }else {
                layer.open({
                    type:1,
                    title: '修改控制时间',
                    content: $('#openEditControlProductBox'),//利用jQuery嵌入弹出层容器
                    area:['430px','270px'],
                    end:function (){
                        $('#openEditControlProductBox').hide()
                    }
                });

            }
        },




    }
})


//监听复选框事件
myTableControl.table.on('checkbox(dataTableControl)',function (obj) {
    let checkStatue = myTableControl.table.checkStatus('dataTableControl')
    let checkedData = JSON.parse(JSON.stringify(checkStatue.data))
    let dataLength = checkStatue.data.length
    selectControlVue.$data.selectedData = []
    for(let i = 0;i< dataLength;i++){
        selectControlVue.$data.selectedData.push({
            "userId":checkedData[i].userId,
        })
    }

    // alert(JSON.stringify(selectControlVue.$data.selectedData))
})

//修改弹窗Vue数据框架
let modifyVue = new Vue({
    el:'#modify_View_editControl',
    data:{
        startDate:'',
        endDate:''
    },

    methods: {
        //修改提交处理
        editCheckAndSubmit:function (event) {
            for(let i = 0;i<selectControlVue.$data.selectedData.length;i++){//为选中元素添加日期时间信息
                selectControlVue.$data.selectedData[i].startDate = modifyVue.$data.startDate
                selectControlVue.$data.selectedData[i].endDate = modifyVue.$data.endDate
            }
            if(this.startDate ===''|| this.endDate===''){
                layer.msg("请选择有效时间！",{
                    time:1500
                })
            }else{
                layer.confirm("确定修改？",function () {
                    layer.closeAll()
                    let url = $('#modifyControlVisitor').attr('action')
                    axios({
                        url:url,
                        method: 'post',
                        data:{
                            modifyInfo: selectControlVue.$data.selectedData
                        }
                    }).then(function (response) {
                        layer.msg(JSON.stringify(response.data),{
                            time:1500
                        })
                        myTableControl.tableFlush(dataSourceControl,controlMethod)
                    })
                })
            }

        }
    }
})


//------------------------------------------------自由用户表--------------------------------------------------------

let myTableUnControl = {
    table:layui.table,
    tableFlush:function (dataSourceUrl,method){
        this.table.render({
            elem:'#dataTableUnControl'
            ,cellMinWidth: 100
            ,height: 616
            ,method: method //请求方式
            ,url: dataSourceUrl //数据接口
            ,page: true//开启分页
            ,autoSort:true
            ,limit:14
            ,size:'lg'
            ,even:true
            ,response:{
                statusCode: 200,
            }
            //动态数据表格
            //如果响应数据格式不符合layui默认要求，则需要用到phraseData
            ,cols: [ [ //表头,两个括号间的空格不能去
                {type:'checkbox',width: '5%'},
                {field: 'index', title: '序号', width:'10%', unresize:true, sort: true },
                {field: 'userId', title: 'ID', width:'35%',unresize:true},
                {field: 'userName', title: '用户名', width:'35%',unresize:true},
                {toolbar: '#uncontrolBar', title: '操作', width:'15%',unresize:true},

            ] ]

        })
    }
}


//表格数据源
layui.use('table',function () {
    unControlMethod = 'get'
    flushUnControlDataSource = dataSourceUncontrol
    myTableUnControl.tableFlush(dataSourceUncontrol,unControlMethod)

    let laydate = layui.laydate;

    //添加弹出层获取日期并将数据存入Vue框架
    laydate.render({
        elem:'#addDateRange',
        range:['#addStartDate','#addEndDate'],
        type: 'datetime',

        done:function (value,date,endDate) {
            let start = JSON.parse(JSON.stringify(date))
            let end = JSON.parse(JSON.stringify(endDate))
            if(!(value === '' || value === undefined || value === null)){
                addControlVue.$data.startDate = start.year+'-'+start.month+'-'+start.date+' '+start.hours+":"+start.minutes+":"+start.seconds
                addControlVue.$data.endDate =  end.year+'-'+end.month+'-'+end.date+' '+end.hours+":"+end.minutes+":"+end.seconds

            }else{
                addControlVue.$data.startDate  = ''
                addControlVue.$data.endDate =  ''
            }

        },
    })
})


//负责自由用户数据表进行查询处理的Vue框架
let unControlVue = new Vue({
    el:'#selectUnControlSubmit',
    data:{
        message:'',
    },

    methods:{
        //查询方法
        selectUnControlClick:function(event) {
            let choice = $("[name='userUnControlChoice']")
            let realChoice = ''
            for(let i = 0;i<choice.length;i++){
                if (choice[i].checked) realChoice = choice[i].value
            }

            if(realChoice === 'byName'){
                if(this.message === ''){
                    layer.msg('请在右侧数据框中输入用户名！',{
                        time:1500
                    })
                }else if(!checkName(this.message)){
                    layer.msg('用户名非法！',{
                        time:1500
                    })
                }else {
                    let urlPrefix = $('#selectUnControlVisitor').attr('action')
                    let url = urlPrefix + realChoice +'/'+this.message
                    myTableUnControl.tableFlush(url,'get')
                    layer.msg('查询成功！',{
                        time:1500
                    })
                }
            }else{
                if(this.message === ''){
                    layer.msg('请在右侧数据框中输入Id号！',{
                        time:1500
                    })
                }else if(!checkId(this.message)){
                    layer.msg('Id号非法非法！',{
                        time:1500
                    })
                }else {
                    let urlPrefix = $('#selectUnControlVisitor').attr('action')
                    let url = urlPrefix + realChoice +'/'+this.message
                    myTableUnControl.tableFlush(url,'get')
                    layer.msg('查询成功！',{
                        time:1500
                    })
                }
            }
        },

        //批量添加控制
        addcontrol:function (event) {
            let addData = addControlVue.$data.addData
            if(addData.length === 0){
                layer.msg('请选中要添加的用户',{
                    time:1500
                })

            }else{
                layer.open({
                    type:1,
                    title: '设置用户许可访问时间',
                    content: jQuery('#openAddControlProductBox'),//利用jQuery嵌入弹出层容器
                    area:['430px','270px'],
                    end:function (){
                        jQuery('#openAddControlProductBox').hide()
                    }
                })
            }
        }
    }

})

//监听数据表表头事件的特定框架
//表头事件为添加控制
myTableUnControl.table.on('tool(dataTableUnControl)',function (obj) {
    let table = myTableUnControl.table
    let data = JSON.parse(JSON.stringify(obj.data))
    let layEvent = obj.event
    switch (layEvent) {
        case 'addControl':
            addControlVue.$data.addData.push({
                'userId':data.userId
            })
            layer.open({
                type:1,
                title: '设置用户许可访问时间',
                content: jQuery('#openAddControlProductBox'),//利用jQuery嵌入弹出层容器
                area:['430px','270px'],
                end:function (){
                    jQuery('#openAddControlProductBox').hide()
                }
            })

            break
    }
})

//负则添加限制的Vue
let addControlVue = new Vue({
    el:'#modify_View_addControl',
    data:{
        startDate:'',
        endDate:'',
        addData:[]
    },

    methods:{

        //添加提交
        addCheckAndSubmit:function (event) {
            if(this.startDate ===''|| this.endDate ===''){
                layer.msg('请输入日期',{
                    time:1500
                })
            }else{
                for(let i = 0;i<this.addData.length;i++){
                    this.addData[i].startDate = this.startDate
                    this.addData[i].endDate = this.endDate
                }

                axios({
                    url:$('#deleteUnControlVisitor').attr('action'),
                    method:'put',
                    data:{
                        addInfo:addControlVue.$data.addData
                    }

                }).then(function (response) {
                    addControlVue.$data.endDate = ''
                    addControlVue.$data.startDate = ''
                    addControlVue.$data.addData = []
                    myTableUnControl.tableFlush(dataSourceUncontrol,unControlMethod)
                    layer.closeAll()
                    layer.msg(JSON.stringify(response.data),{
                        time:1500
                    })
                })


            }
        }
    }
})


//监听复选框选择事件
myTableUnControl.table.on('checkbox(dataTableUnControl)',function (obj) {
    let checkStatue = myTableUnControl.table.checkStatus('dataTableUnControl')
    let checkedData = JSON.parse(JSON.stringify(checkStatue.data))
    let dataLength = checkStatue.data.length
    addControlVue.$data.addData = []
    addControlVue.$data.startDate = ''
    addControlVue.$data.endDate = ''
    for(let i = 0;i< dataLength;i++){
        addControlVue.$data.addData.push({
            "userId":checkedData[i].userId,
        })
    }

    // alert(JSON.stringify(selectControlVue.$data.selectedData))
})









//------------------------------------------------------不涉及到数据处理的事件用jQuery处理--------------------------------------------------------------------
$(document).ready(function () {

    /*
    -------------------------------受控表--------------------------------
     */
    //刷新数据
    $('#flushControlButton').click(function (){
        selectControlVue.$data.selectedData = []
        myTableControl.tableFlush(flushControlDataSource,controlMethod)
        layer.msg("数据已经刷新",{
            time:1500
        })
    })

    $('#editCancel').click(function (){
        selectControlVue.$data.selectedData = []
        layer.closeAll()
        layer.msg("您已取消修改",{
            time:1500
        })
    })



    /*
    -----------------------------自由用户---------------------------
     */

    //刷新数据
    $('#flushUnControlButton').click(function (){
        unControlVue.$data.message = ''
        myTableUnControl.tableFlush(flushUnControlDataSource,unControlMethod)
        layer.msg("数据已经刷新",{
            time:1500
        })
    })


})
